/**
 * 
 */
package br.com.sglf.support;

import java.text.NumberFormat;
import java.util.Locale;
import java.util.regex.Pattern;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 * @author macbook
 *
 */
@FacesConverter(value = "converteValor")
public class ConverteValor implements Converter  { 
	public static final Locale BRAZIL = new Locale("pt","BR");  
    /**
     * @param arg0
     * @param arg1
     * @param valorTela
     * @return
     * @throws ConverterException
     */
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String valorTela) throws ConverterException {
        if (valorTela == null || valorTela.toString().trim().equals("")){
            return null;

        }else{
            valorTela = valorTela.replaceAll(Pattern.quote("."), "");

            try{
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(2);
                nf.setMinimumFractionDigits(2);
                String valorDouble = valorTela.replace(",", ".");
                Double retorno = Double.parseDouble(valorDouble);
                return retorno;
            }catch (Exception e) {
                return 0.0d;
            }
        }
    }

    /**
     * @param arg0
     * @param arg1
     * @param valorTela
     * @return
     * @throws ConverterException
     */
    public String getAsString(FacesContext arg0, UIComponent arg1, Object valorTela) throws ConverterException {
        if (valorTela == null || valorTela.toString().trim().equals("")) {
            return "";

        }else{ 
	        Locale locale = BRAZIL;
	        String string = NumberFormat.getCurrencyInstance(locale).format(Double.valueOf(valorTela.toString())); 
            //NumberFormat nf = NumberFormat.getInstance(new Locale("pt", "BR"));
            //nf.setMaximumFractionDigits(2);
            //return nf.format(Double.valueOf(valorTela.toString()));
            return string;
        }
    }
}
